package us.sunrisemorning.pixivbrower.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import us.sunrisemorning.pixivbrower.model.Config;

public class ConfigService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    public final Config dao = new Config().dao();

    public synchronized void setConfig(String name, String value) {
        Config config = dao.findById(name);
        if (config == null) {
            config = new Config();
            config.setName(name);
            config.save();
        }
        config.setValue(value);
        config.update();
    }

    public void setBooleanConfig(String name, boolean value) {
        setConfig(name, value ? "true" : "false");
    }

    public String getConfig(String name) {
        Config config = dao.findById(name);
        if (config != null) {
            return config.getValue();
        }
        return null;
    }

    public String getConfig(String name, String defaultValue) {
        String value = getConfig(name);
        return value == null ? defaultValue : value;
    }

    public int getIntegerConfig(String name) {
        String value = getConfig(name);
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException e) {
            logger.debug("ConfigService cannot convert integer value.", e);
            return 0;
        }
    }

    public boolean getBooleanConfig(String name) {
        String value = getConfig(name);
        return "true".equals(value);
    }
}
